package com.chwl.framework.springboot.grpc.config;

import com.chwl.framework.grpc.annotation.GrpcService;
import com.chwl.framework.grpc.utils.ClassNameUtils;
import com.chwl.framework.springboot.grpc.GrpcServiceProxy;
import com.chwl.framework.springboot.grpc.service.UserDefinedInvocationHandler;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.util.StringUtils;

import java.util.Set;
import java.util.logging.Logger;

/**
 * <p>功能:</p>
 *
 * @
 * @date:2018-07-14 下午6:49<br/>
 * @version:1.0 <br/>
 */
public class ProxyUtil {
    static Logger log = Logger.getLogger(ProxyUtil.class.getName());

    static void registBeans(BeanFactory beanFactory, Set<BeanDefinition> beanDefinitions) {
        for (BeanDefinition beanDefinition : beanDefinitions) {
            String className = beanDefinition.getBeanClassName();
            if (StringUtils.isEmpty(className)) {
                continue;
            }
            try {
                DefaultListableBeanFactory defaultListableBeanFactory = ((DefaultListableBeanFactory) beanFactory);
                // 创建代理类
                Class<?> target = Class.forName(className);
                InvocationHandler invocationHandler = new GrpcServiceProxy<>(target, defaultListableBeanFactory.getBean(UserDefinedInvocationHandler.class), defaultListableBeanFactory);
                Object proxy = Proxy.newProxyInstance(GrpcService.class.getClassLoader(), new Class[]{target}, invocationHandler);

                // 注册到 Spring 容器
                String beanName = ClassNameUtils.beanName(className);
                defaultListableBeanFactory.registerSingleton(beanName, proxy);
            } catch (ClassNotFoundException e) {
                log.warning("class not found : " + className);
            }
        }
    }
}